package examples.actors

import scala.actors.{Actor, Exit}
import scala.actors.Actor._

object links extends App {

  case object Stop

  actor {
    println("main(" + self + ")")

    /**
     * main(scala.actors.Actor$$anon$1@3e0694a5)
     * starting last actor (scala.actors.Actor$$anon$1@6743e87d)
     * starting actor 1 self(scala.actors.Actor$$anon$1@23d0f70a),a(scala.actors.Actor$$anon$1@6743e87d)
     * starting actor 2 self(scala.actors.Actor$$anon$1@6c0ac3e4),a(scala.actors.Actor$$anon$1@23d0f70a)
     * Actor 2 received Stop
     * Actor 1 received Stop
     * Last actor now exiting
     * Actor 1 received Exit(scala.actors.Actor$$anon$1@6743e87d,'abnormal)
     * Actor 2 received Exit(scala.actors.Actor$$anon$1@3e0694a5,'normal)
     */
//        val start = link(p(2))
//        start ! Stop

    /**
     * main(scala.actors.Actor$$anon$1@7bf5f379)
     * starting last actor (scala.actors.Actor$$anon$1@4fad81d2)
     * starting actor 2 self(scala.actors.Actor$$anon$1@35523de0),a(scala.actors.Actor$$anon$1@2a5c5879)
     * starting actor 1 self(scala.actors.Actor$$anon$1@2a5c5879),a(scala.actors.Actor$$anon$1@4fad81d2)
     * Actor 1 break .
     * Actor 2 received Exit(scala.actors.Actor$$anon$1@7bf5f379,'break)
     */
    val p0 = top1()
    val p1 = top(p0, 1)
    val p2 = top(p1, 2)
    link(p2)
    p1 ! "break"
  }

  def p(n: Int): Actor =
    if (n == 0) top1()
    else top(p(n - 1), n)

  def top(a: Actor, n: Int): Actor = actor {
    println("starting actor " + n + " self(" + self + "),a(" + a + ")")
    //捕捉非 'normal Exit
    self.trapExit = true
    link(a)
    loop {
      receive {
        case ex@Exit(from, reason) =>
          println("Actor " + n + " received " + ex)
          exit('finished)
        case "break" =>
          println("Actor " + n + " break .")
          exit('break)
        case any =>
          println("Actor " + n + " received " + any)
          a ! any
      }
    }
  }

  def top1(): Actor = actor {
    println("starting last actor" + " (" + self + ")")
    receive {
      case Stop =>
        println("Last actor now exiting")
        exit('abnormal)

      /**
       * 没走到
       * @deprecated
       */
      case any =>
        println("Last actor received " + any)
        top1()
    }
  }
}
